import { BaseView } from './baseview.js'

import { domain_helper } from '../domain_helper.js'

function merge_domain(dms, and_or) {
  const [dm1, dm2] = dms.reduce(
    (acc, cur) => {
      if (cur && cur.length) {
        const [a1, a2] = acc
        if (a2) {
          if (a1) {
            acc[0] = [...a1, and_or, ...a2]
          } else {
            acc[0] = a2
          }
        }

        acc[1] = cur
      }

      return acc
    },
    [null, null]
  )

  const dm3 = dm1 && dm2 ? [and_or, ...dm1, ...dm2] : dm1 || dm2 || []

  return dm3
}

function make_domain_one_field(val) {
  const vs = val.value
  const filter_domain = val.filter_domain || [[val.name, 'ilike', { self: {} }]]

  const vs2 = vs.map(item =>
    domain_helper.domain_maker(filter_domain, { self: item })
  )

  const dm3 = merge_domain(vs2, '|')
  return dm3
}

function make_domain_one_filter(val) {
  const vs2 = Object.keys(val.value)
    .filter(item => val.value[item].checked)
    .map(item => {
      const mydomain = val.value[item].domain
      const mydomain2 = domain_helper.domain_maker(mydomain, {})
      return mydomain2
    })

  const dm3 = merge_domain(vs2, '|')
  return dm3
}

function make_domain_one(val) {
  if (val.tagname === 'field') {
    return make_domain_one_field(val)
  } else if (val.tagname === 'filter') {
    return make_domain_one_filter(val)
  } else {
    console.log('errror ')
    return []
  }
}

function make_domain(values) {
  const values2 = Object.keys(values).map(item => make_domain_one(values[item]))

  const dm3 = merge_domain(values2, '&')
  return dm3
}

export class SearchView extends BaseView {
  constructor(payload = {}) {
    super(payload)

    this.values = {}
  }

  get domain() {
    // console.log(this.values)
    const dm3 = make_domain(this.values)

    // console.log(dm3)
    return dm3
  }

  _get_sheet() {
    // console.log(this.config)
    const { arch = {} } = this.config
    const { sheet = {} } = arch

    const for_view = 'search'
    const kws = { for_view }
    return this.get_arch_for_node(sheet, kws)
  }

  get_sheet() {
    const children = this._get_sheet()

    // console.log('get_sheet', children, this.metadata)

    if (Object.keys(children).length) {
      return {
        children,
        nodename: 'sheet',
        tagname: 'sheet'
      }
    } else {
      return {
        children: {
          field_name: {
            string: this.metadata.name.string,
            name: 'name',
            meta: this.metadata.name,
            nodename: 'field_name',
            tagname: 'field'
          }
        },
        nodename: 'sheet',
        tagname: 'sheet'
      }
    }
  }

  onchange(val) {
    // console.log('onchange', val)
    this.values = val
  }

  get_default() {
    const items = this.get_sheet().children

    const ctx = this.context
    const search_default = Object.keys(ctx)
      .filter(item => item.slice(0, 15) === 'search_default_')
      .reduce((acc, cur) => {
        acc[cur.slice(15)] = ctx[cur]
        return acc
      }, {})

    // console.log(this.context, search_default)
    return Object.keys(items).reduce((acc, cur) => {
      const { meta, default: default1, children, ...done } = items[cur]

      if (done.tagname === 'field') {
        acc[cur] = { ...done, value: [] }
      } else if (done.tagname === 'filter') {
        const children2 = Object.keys(children).reduce((acc, cur) => {
          acc[cur] = { ...children[cur], checked: cur in search_default }
          return acc
        }, {})

        acc[cur] = { ...done, value: children2 }
      }

      return acc
    }, {})
  }
}

// field:  {
//   name,
//   code
// }
// filter: {
//   my: { me },
//   pay: { notpay, paying, payed },
//   status: { draft, done },
//   date: { thisyear, lastyear },
// }
//
// ============================
// and,
//   [ or, name1, or, name2, name3 ]
// and,
//   [ or, code1, or, code2, code3 ]
// and,
//   [ me ]
// and,
//   [ or, notpay, or, paying, payed ]
// and,
//   [ or, draft, done ]
//   [ or, thisyear, lastyear ]
//
// ================================
// name: [ or, name1, or, name2, name3 ]
// --------------------------------
// name.1
//    [ [ name, like, self2 ] ]
// name.2
//    [ [ name, like, self2 ] ]
// name.3
//    [ [ name, like, self3 ] ]
// --------------------------------
// name.1
//    [ or, [ display_name, like, self1 ], [ parent_name, like, self1 ] ]
// name.2
//    [ or, [ display_name, like, self2 ], [ parent_name, like, self2 ] ]
// ==================================
// my: [ me ]
// --------------------------------
// my.me
//    [user_id, =, uid]
// ==================================
// pay:  [ or, notpay, or, paying, payed ]
// --------------------------------
// pay.notpay
//       [ or, [], [] ]
// pay.paying
//       [ [] ]
// pay.payed
//       [ and, [], [] ]
// ==================================
// status: [ or, draft, done ]
// --------------------------------
// status.draft
//       [ [ state, in, [draft, ...] ] ]
// status.done
//       [ [ state, =, done ] ]
// ==================================
// date: [ or, thisyear, lastyear ]
// --------------------------------
// date.thisyear
//       [ and, [ date, >=, 2023-12-31 16:00:00 ], [ date, <=, 2024-12-31 15:59:59]  ]
// date.lastyear
//       [ and, [ date, >=, 2022-12-31 16:00:00 ], [ date, <=, 2023-12-31 15:59:59]  ]

// const s = [
//   '&',
//   '|',
//   ['journal_id', '=', false],
//   ['journal_id.type', '=', 'bank'],
//   '&',
//   '|',
//   ['line_ids', '=', []],
//   '|',
//   ['is_valid', '=', false],
//   ['is_complete', '=', false],
//   '&',
//   '|',
//   '&',
//   ['date', '>=', '2023-01-01'],
//   ['date', '<=', '2023-12-31'],
//   '&',
//   ['date', '>=', '2024-01-01'],
//   ['date', '<=', '2024-12-31'],
//   '|',
//   ['name', 'ilike', '1'],
//   ['name', 'ilike', '2']
// ]
